package cn.shenlong.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.shenlong.common.Constants;

public class UploadUtil {

	// 支持的图片格式
	public static String supportedVideoFilesFormats[] = { "png", "bmp", "jpeg",
			"jpg", "gif" };

	private static Logger logger = Logger.getLogger(UploadUtil.class);

	/**
	 * 通用上传图片方法
	 * 
	 * @param request
	 * @param url
	 *            ，可以为空， 用户指定的相对路径 比如 “u/server/contentimg” ,前后都不能有“/”，为了方便后期维护
	 *            ，路径必须是已经存在的文件夹，
	 * @return
	 * @throws Exception
	 */
	public static List<Map<String, Object>> uploadImage(
			HttpServletRequest request, String url) throws Exception {

		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		try {

			List<MultipartFile> uploadFiles = getUploadFiles(request);
			String dir = Constants.APPLICATION_URL;

			if (!StringUtil.isBlank(url)) {
				url = url + "/";
			} else {
				url = "u/";
			}
			for (int i = 0; i < uploadFiles.size(); i++) {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				MultipartFile file = uploadFiles.get(i);
				if (!isImageFile(file.getOriginalFilename())) {
					continue;
				}
				// 先放入临时文件夹
				String imagePath = saveFile(file, dir, url);
				resultMap.put("imagePath", imagePath);
				resultMap.put("result", true);
				resultList.add(resultMap);
			}

		} catch (Exception e) {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			logger.error(e);

			resultMap.put("result", false);
			resultList.add(resultMap);
			throw e;
		}
		return resultList;
	}

	/**
	 * ueditor编辑器专用显示口
	 * 
	 * @param list
	 * @param response
	 */
	public static void showImageForUeditor(List<Map<String, Object>> list,
			HttpServletResponse response) {
		try {

			// 最终打印到页面
			if (list != null && list.size() > 0) {
				Map<String, Object> resultMap = list.get(0);
				if (resultMap.get("imagePath") != null)
					pringWriterToPage(
							"{ \"url\":\""
									+ resultMap.get("imagePath")
									+ "\", \"title\":\"\", \"state\":\"SUCCESS\" }",
							response);

			} else {
				pringWriterToPage(
						"{ \"url\":\"\", \"title\":\"\", \"state\":\"文件类型必须是png,bmp,jpeg,jpg,gif\" }",
						response);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			pringWriterToPage(
					"{ \"url\":\"\", \"title\":\"\", \"state\":\"文件类型必须是png,bmp,jpeg,jpg,gif!\" }",
					response);

		}
	}

	/**
	 * 删除本地存储的文件
	 * 
	 * @param request
	 * @param url
	 *            文件的相对路径位置
	 */
	public static void deleteForUrl(String url) {
		if (StringUtil.isBlank(url) || url.indexOf("http") == 0) {
			return;
		}
		String dir = Constants.APPLICATION_URL;
		dir = dir + url;
		File file = new File(dir);
		// 判断目录或文件是否存在
		if (!file.exists()) { // 不存在返回
			return;
		} else {
			// 判断是否为文件
			if (file.isFile()) { // 为文件时调用删除文件方法
				file.delete();
			}
		}
	}

	/**
	 * 删除图片文件
	 * 
	 * @param request
	 * @param html
	 */
	public static void deleteImgForHtml(String html) {
		if (StringUtil.isBlank(html)) {
			return;
		}
		try {
			Document doc = Jsoup.parse(html);
			Elements imgs = doc.getElementsByTag("img");
			for (Element img : imgs) {
				try {
					String linksHref = img.attr("src");
					deleteForUrl(linksHref);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 保存文件
	 * 
	 * @param file
	 * @param dir
	 *            存储的根目录
	 * @param url
	 *            相对路径
	 * @return 文件相对路径
	 */
	private static String saveFile(MultipartFile file, String dir, String url)
			throws Exception {
		dir = dir + url;

		String tmpFileName = String.valueOf(System.currentTimeMillis());
		String filename = file.getOriginalFilename();
		tmpFileName += ("." + filename.substring(filename.lastIndexOf(".") + 1));// 取出后缀名
		File tempFile = new File(dir, tmpFileName);
		FileOutputStream out = new FileOutputStream(tempFile);
		out.flush();
		out.write(file.getBytes());
		out.close();
		return "/" + url + tmpFileName;

	}

	/**
	 * 获得批量的上传文件集合
	 * 
	 * @param request
	 * @return
	 */
	private static List<MultipartFile> getUploadFiles(HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		List<MultipartFile> files = new ArrayList<MultipartFile>();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile mf = entity.getValue();
			files.add(mf);
		}
		return files;
	}

	private static boolean isImageFile(String file) {
		if (file == null || file == "") {
			return false;
		}
		String filename = file.toString();
		String file_ext = filename.substring(filename.lastIndexOf(".") + 1);// 取出后缀名
		if (Arrays.asList(supportedVideoFilesFormats).contains(
				file_ext.toLowerCase())) {
			return true;
		}
		return false;
	}

	/**
	 * 打印到页面上
	 * 
	 * @param str
	 */
	private static void pringWriterToPage(String str,
			HttpServletResponse response) {
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(str);
			out.flush();
			out.close();
			return;
		} catch (IOException e1) {

			e1.printStackTrace();
			return;
		}
	}

}
